package util

import (
	"bytes"
	"crypto/md5"
	"fmt"
	"strings"
)

func Split(s,sep string) []string{
	if len(s)>0{
		strlist := strings.Split(s, sep)
		out := []string{}
		for _, str:= range strlist{
			if(len(str)>0){
				out=append(out, str)
			}
		}
		return out
	}
	return []string{""}
}

func Join(strs []string, sep string) string {
	var build strings.Builder
	var i int = 0
	for _, str := range strs {

		if len(str) > 0 {
			if i != 0 {
				build.WriteString(sep)
			}
			build.WriteString(str)
			i += 1

		}
	}
	return build.String()
}

func IsEmpty(str string) bool {
	return !(len(str) > 0)
}

func ToMd5(str string) string {
	return fmt.Sprintf("%x", md5.Sum([]byte(str)))
}

func ToMd5WithSalt(origin string, salt string) string {
	var build bytes.Buffer
	i, len1, len2 := 0, len(origin), len(salt)
	for ; i < len1 || i < len2; i++ {
		if i < len1 {
			build.WriteByte(origin[i])
		}
		if i < len2 {
			build.WriteByte(salt[i])
		}
	}

	return ToMd5(build.String())
}

// func ReplaceAll(s, rep string) string {

// }

// replace first sub string match old to new
func Replace(s, old string, new string) string {
	l1, l2 := len(s), len(old)
	if l1 > 0 && l2 > 0 {
		var build bytes.Buffer
		i := 0
		for i < l1 {
			if s[i] == old[0] && i+l2 < l1 && s[i:i+l2] == old {
				build.WriteString(new)
				i += l2
				build.WriteString(s[i:])
				break
			}
			build.WriteByte(s[i])

			i += 1
		}
		return build.String()
	}

	return s
}
